export const useUploadFile = (accept?: string) => {
  const input = document.createElement('input');
  input.hidden = true;
  input.type = 'file';

  input.accept = accept || '*';
  input.click();
  return new Promise<File>(res => {
    input.onchange = () => {
      const { files } = input;
      if (files?.length === 1) {
        res(files[0]!);
      }
      input.remove();
    };
  });
};

export const toBase64 = (file: File) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  return new Promise<string>(res => {
    reader.onload = () => {
      res(reader.result as string);
    };
  });
};

export const toText = (file: File) => {
  const reader = new FileReader();
  reader.readAsText(file);
  return new Promise<string>(res => {
    reader.onload = () => {
      res(reader.result as string);
    };
  });
};

// 判断的是否是JSON字符串
export const isJson = (str: string): boolean => {
  try {
    const obj = JSON.parse(str);
    // 等于这个条件说明就是JSON字符串 会返回true
    if (typeof obj === 'object' && obj) {
      return true;
    }
    // 不是就返回false
    return false;
  } catch (e) {
    return false;
  }
};
export const base64toFile = (base64String: string, filename: string): File => {
  // 解码base64字符串
  const byteCharacters = atob(base64String);
  const byteNumbers = new Array(byteCharacters.length);
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);

  // 创建Blob对象
  const blob = new Blob([byteArray], { type: 'application/octet-stream' });

  // 创建文件对象
  const file = new File([blob], filename, { type: 'application/octet-stream' });

  return file;
};
